package cn.jinbyte.core.handler.masking;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;

/**
 * 自定义脱敏序列化器
 */
public class MaskingSerializer extends JsonSerializer<String> implements ContextualSerializer {
    private MaskingStrategy strategy;

    public MaskingSerializer() {
        // 默认构造函数
    }

    private MaskingSerializer(MaskingStrategy strategy) {
        this.strategy = strategy;
    }

    @Override
    public void serialize(String value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
        if (value == null) {
            gen.writeNull();
            return;
        }
        gen.writeString(strategy.mask(value));
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider prov, BeanProperty property) throws JsonMappingException {
        if (property == null) {
            return prov.findNullValueSerializer(null);
        }

        MaskField annotation = property.getAnnotation(MaskField.class);
        if (annotation == null) {
            annotation = property.getContextAnnotation(MaskField.class);
        }

        if (annotation != null) {
            return new MaskingSerializer(annotation.strategy());
        } else {
            return prov.findValueSerializer(property.getType(), property);
        }
    }
}